package com.xh.jf_blog.controller;

import com.google.code.kaptcha.Producer;
import com.xh.jf_blog.bean.Code;
import com.xh.jf_blog.common.exception.RTException;
import com.xh.jf_blog.common.util.R;
import com.xh.jf_blog.service.CodeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author PangJunjie
 * @Date 2024/1/31/031
 */
@Controller
public class KaptchaController {
    @Autowired
    private Producer producer;
    @Autowired
    private CodeService codeService;

    @GetMapping("/kaptcha.jpg")
    public void kaptchaImg(HttpServletResponse response, String uuid) throws IOException {
        if (StringUtils.isEmpty(uuid)) {
            throw new RTException("uuid不能为空！");
        }
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        /*获取验证码*/
        String text = producer.createText();
        Code code = new Code();
        code.setCode(text);
        code.setUuid(uuid);
        codeService.saveCode(code);
        /*生成图片*/
        BufferedImage bi = producer.createImage(text);
        ServletOutputStream out = response.getOutputStream();
        /*输出到浏览器*/
        ImageIO.write(bi, "jpg", out);
        /*关闭流*/
        out.flush();
        out.close();
    }

    @GetMapping("/clear/cache")
    @ResponseBody
    public R clearCache() {
        codeService.clear();
        return R.ok();
    }
}
